//
//  SCDownloadManager.m
//  Shuaiche
//
//  Created by xiangtao on 2025/2/7.
//  Copyright © 2025 ShuaiChe. All rights reserved.
//

#import "SCDownloadManager.h"

@implementation SCDownloadManager

+ (instancetype)sharedInstance {
    static SCDownloadManager *sSharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sSharedInstance = [SCDownloadManager manager];
    });
    return sSharedInstance;
}

- (NSURLSessionDownloadTask *)downloadTaskWithUrl:(NSString *)urlString version:(NSString *)version progress:(void (^)(NSProgress *downloadProgress))downloadProgressBlock destination:(NSString *)targetFilePath completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{
    LogInfo(@"targetFilePath = %@",targetFilePath);
    
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    
    //2.下载文件
    
    /*
     
     第一个参数:请求对象
     
     第二个参数:progress 进度回调 downloadProgress
     
     第三个参数:destination 回调(目标位置)
     
     有返回值
     
     targetPath:临时文件路径
     
     response:响应头信息
     
     第四个参数:completionHandler 下载完成之后的回调
     
     filePath:最终的文件路径
     
     */
    
    NSURLSessionDownloadTask *download = [super downloadTaskWithRequest:request progress: downloadProgressBlock destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSString *suggestedFilename = response.suggestedFilename;
        NSArray *arr = [suggestedFilename componentsSeparatedByString:@"."];
        if (arr.count < 2) {
            return nil;
        }
        NSString *newFileName;
        if (version) {
            newFileName = [NSString stringWithFormat:@"%@%@.%@",arr[0],version,arr[1]];
        } else {
            newFileName = suggestedFilename;
        }
        
        NSString *fullPath = [targetFilePath stringByAppendingPathComponent:newFileName];
        if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath]) {
            NSURL *fullPathURL = [NSURL fileURLWithPath:fullPath];
            [[NSFileManager defaultManager] removeItemAtURL:fullPathURL error:NULL];
        }
        NSURL *fileUrl = [NSURL fileURLWithPath:fullPath];
        
        return fileUrl;
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        LogInfo(@"filePath = %@",filePath);
        if (completionHandler) {
            completionHandler(response, filePath, error);
        }
    }];
    
    //3.执行Task
    
    [download resume];
    
    return download;
}

- (BOOL)clearCacheWithFilePath:(NSString *)path{
    
    NSError *error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
    if (error) {
        return NO;
    }
    return YES;
}


@end
